﻿using Newtonsoft.Json;
using SqlServerWebServerConsole;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;

namespace Server_NetFramework_Door
{
    /// <summary>
    /// Alcohol 的摘要说明
    /// </summary>
    public class Alcohol : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.AddHeader("Access-Control-Allow-Origin", "*");
            context.Response.ContentType = "text/plain";
            
            var action= context.Request.QueryString["action"];
            //没有指定操作类型：默认就是获取数目
            if (String.IsNullOrEmpty(action))
            {
                int count = (int)SqlHelper.ExecuteScalar("select count(*) from cqxx");
                context.Response.Write($"{count}");
            }
            else if (action=="num")
            {
                //获取多少条数据
                var num = context.Request.QueryString["num"];
                if (string.IsNullOrEmpty(num)){
                    context.Response.Write("num必须指定数目");
                }
                else
                {
                    try
                    {
                        int iNum = Convert.ToInt32(num);
                        DataTable dt = SqlHelper.ExecuteDataTable("select top " + iNum + " * from cqxx order by id desc");
                        context.Response.Write(JsonConvert.SerializeObject(dt));

                    }
                    catch (Exception e) {
                        context.Response.Write("num必须指定数目且是数字类型："+e.Message);
                    }
                }


            }
            else
            {
                context.Response.Write("请求参数错误");
            }

            
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}